<template>
  <div>
    <div class="g-cur">
    <div class="wp">
      <NuxtLink to="/" class="a">创作中心</NuxtLink><span> / </span>
      <span class="s">创建作品</span>
    </div>
  </div>
  <div class="wp">
    <div class="createW">
      <!-- tab -->
      <ul class="ul-steps">
        <li class="act">
          <div class="idx">1</div>
          <div class="p">书籍信息</div>
        </li>
        <li class="act">
          <div class="idx">2</div>
          <div class="p">版权信息</div>
        </li>
        <li class="act">
          <div class="idx">3</div>
          <div class="p">打印信息</div>
        </li>
        <li :class="$route.meta.cpos >= 3 ? 'act' : ''">
          <div class="idx">4</div>
          <div class="p">价格信息</div>
        </li>
      </ul>
      <!-- 内容 -->
      <div class="print-info">
        <div class="group">
          <div class="title">
            <div class="h3">上传PDF文件<em>*</em></div>
          </div>
          <div class="p">上传文件必须是PDF格式，包括书的所有内部内容。</div>
          <div class="upload">
            <a-upload-dragger
              v-model:fileList="fileList"
              name="file"
              :auto-upload="false"
               :beforeUpload="handleChangeImg1"
              @drop="handleDrop"
            >
              <p class="drag-icon">
                <img src="/images/c-up.svg" alt="">
              </p>
            
              <p class="p">
                选择一个文件或拖放文件到此处
              </p>
            </a-upload-dragger>
          </div>
          <div class="up-if">
            <p>
              文件信息<br> 格式：PDF <br />
              尺寸：US Letter (8.5 x 11 in / 216 x 279 mm)<br />
              页数：200<br />
              <br />
              注：<br> 1、根据上传PDF自动获取书籍尺寸大小及页数；<br />
              2、PDF页数2-800页，超过800页请修改PDF源文件
            </p>
          </div>
        </div>
        <div class="group">
          <div class="title">
            <div class="h3">纸质书封面<em>*</em></div>
            <span class="down">下载示例模版</span>
            <span class="down">尺寸说明</span>
          </div>
          <div class="p">请按照下方提供样式上传纸质书封面</div>
          <div class="upload1">
            <a-upload
              v-model:file-list="fileList1"
              :auto-upload="false"
              list-type="picture-card"
              :beforeUpload="handleChangeImg"
              @preview="handlePreview"
            >
              <div>
                <plus-outlined />
              </div>
            </a-upload>
            <a-modal
              :visible="previewVisible"
              :title="previewTitle"
              :footer="null"
              @cancel="handleCancel"
            >
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
          <div class="p">
            封面要求：File Type: PDF Page Count: 1 Dimensions: 19.875 x 12.75in /
            504.82mm x 323.85mm <br />
            Spine Width: 1.125in / 28.58mm Fonts: Embedded Layers: Flattened
          </div>
        </div>
        <div class="group">
          <div class="title">
            <div class="h3">书籍尺寸&页数<em>*</em></div>
          </div>
          <div class="p">书籍尺寸和页数取决于您上传的内部文件。若要更改这些内容，请上传修订后的PDF文件。</div>
          <div class="selbox">
            <div class="item">
              <div class="s">选择书籍尺寸：</div>
              <div class="rr">
                <a-select
                  v-model:value="formState.interiorColor"
                  style="width: 168px"
                  placeholder="选择书籍尺寸："
                >
                  <a-select-option v-for="(item,index) in selectList.types.colour" :key="index" :value="item">{{ item }}</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="item">
              <div class="s">文件页数：</div>
              <div class="rr">
                <a-input v-model:value="value" placeholder="请输入" />
              </div>
            </div>
            
          </div>
        </div>
        <div class="group">
          <div class="title">
            <div class="h3">设置打印规格<em>*</em></div>
          </div>
          <div class="p">设置打印规格供用户打印纸质书时选择，最多1项</div>
          <div class="selbox">
            <div class="item">
              <div class="s">内饰颜色：</div>
              <div class="rr">
                <a-select
                  v-model:value="formState.interiorColor"
                  style="width: 168px"
                  placeholder="选择内饰颜色"
                >
                  <a-select-option v-for="(item,index) in selectList.types.colour" :key="index" :value="item">{{ item }}</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="item">
              <div class="s">纸张类型：</div>
              <div class="rr">
                <a-select
                  v-model:value="formState.paperType"
                  style="width: 168px"
                  placeholder="选择纸张类型"
                >
                <a-select-option v-for="(item,index) in selectList.types.category" :key="index" :value="item">{{ item }}</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="item">
              <div class="s">装订样式：</div>
              <div class="rr">
                <a-select
                  v-model:value="formState.bookBinding"
                  style="width: 168px"
                  placeholder="选择装订样式"
                >
                <a-select-option value="COIL_BOUND">COIL_BOUND</a-select-option>
                <a-select-option v-for="(item,index) in selectList.types.pattern" :key="index" :value="item">{{ item }}</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="item">
              <div class="s">封面装饰：</div>
              <div class="rr">
                <a-select
                  v-model:value="formState.coverFinish"
                  style="width: 168px"
                  placeholder="选择纸封面装饰"
                >
                <a-select-option v-for="(item,index) in selectList.types.cover" :key="index" :value="item">{{ item }}</a-select-option>
                </a-select>
              </div>
            </div>
          </div>
        </div>

        <div class="bot-opts">
          <NuxtLink :to="'/copyright?id='+id+'&from=3'" class="btn">返回上一步</NuxtLink>
          <a @click="save()" class="btn btn1">下一步</a>
        </div>
      </div>
    </div>
  </div>
  </div>
</template> 

<script setup>
import { reactive, ref, onMounted } from 'vue';

import { PlusOutlined } from '@ant-design/icons-vue';
import request from '~/services/request'
import { message } from 'ant-design-vue';
import {RouterLink, RouterView, useRouter} from 'vue-router'
const router = useRouter()
const route = useRoute()  
const S3 = ref(null)
const id = ref(route.query.id)
const status=ref('')
const status1=ref('')
const handleChange = info => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};
const handleDrop = e => {
  console.log(e);
};

const fileList = ref([]);

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const selectList = reactive({
  types:{}
});
const fileList1 = ref([]);
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview1=async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const formState = reactive({
  id:id.value
});
function save(){
  if(status.value=='VALIDATED'&&status1.value=='VALIDATED'){
    if(route.query.from==4){
    request.patch_books_id_specification(formState).then((res)=>{
    router.push('/priceInfo?id='+id.value+'&from=3');
  })
  }else{
    request.post_books_id_specification(formState).then((res)=>{
    router.push('/priceInfo?id='+id.value+'&from=3');
  })
  }
  }else{
    message.error({
      content: () => '正在验证请稍等...',
      class: 'custom-class',
      style: {
        marginTop: '20vh',
      },
    });
  }
}
async function handleChangeImg(file) {
  status.value==''
  const uploadResult = await S3.value.putObject({
    Bucket: 'silentberry.co',
    Key: file.uid,
    Body: file,
    ContentType: file.type
  }).promise()
   getImageUrl(file.uid,'coverUrl')
   return false
}
async function handleChangeImg1(file) {
  status1.value==''
  const uploadResult = await S3.value.putObject({
    Bucket: 'silentberry.co',
    Key: file.uid,
    Body: file,
    ContentType: file.type
  }).promise()
  debugger
   getImageUrl(file.uid,'sourceUrl')
   return false
}
async function getData(id) {
  var timer =setInterval(()=>{
    if(status.value=='VALIDATED'){
      clearInterval(timer);
    }else{
      request.get_lulu_validate_cover_id({id:id}).then(res => {
        status.value=res.status
      })
    }
  },1000)
}
async function getData1(id) {
  var timer1 =setInterval(()=>{
    if(status1.value=='VALIDATED'){
      clearInterval(timer1);
    }else{
      request.get_lulu_validate_source_id({id:id}).then(res => {
        status1.value=res.status
      })
    }
  },1000)
}
 
 
// 调用函数并等待结果
function getImageUrl(key,urlKey) {
  debugger
  if (key) {
    const params = {
      Bucket: 'silentberry.co',
      Key: key
    }

    S3?.value?.getSignedUrl('getObject', params, (err, url) => {
      if (err) {
        console.error('Error getting signed URL:', err)
      } else {
        // fileList1.value = fileList1.value.filter(item => item.url != undefined)
        console.log('Signed URL:', url)
        if(urlKey!='sourceUrl'){
          request.post_lulu_validate_cover({[urlKey]:url }).then(res => {
          formState.coverValidateId=res.id
          formState.coverUrl=key
          getData(res.id)
        })
        }else{
          request.post_lulu_validate_source({[urlKey]:url }).then(res => {
          formState.sourceValidateId=res.id
          formState.sourceUrl=key
          getData1(res.id)
        })
      }
   
        // fileList1.value.push(
        //   {
        //     uid: Math.random(),
        //     name: key,
        //     uid:key,
        //     status: 'done',
        //     url: url,
        //   }
        // )
      }
    })
  }
}
onMounted(() => {
  if (id.value) {
    request.get_books_by_id({ id: id.value }).then(res => {
      for (const key in formState) {
        if (Object.hasOwnProperty.call(formState, key)) {
          formState[key] = res[key];
        }
      }
    })
  }
  let script = document.createElement('script');
  script.src = '/aws-sdk-2.1673.0.min.js';
  script.onload = () => {
    // 脚本加载完毕后的回调
    AWS.config.update({
      accessKeyId: 'AKIA23OJK3X3H2OI5MLV',
      secretAccessKey: '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',
      region: 'ap-northeast-1'
    })

    S3.value = new AWS.S3({
      apiVersion: "2006-03-01",
      params: { Bucket: 'silentberry.co' }
    })
  };
  document.body.appendChild(script);
  request.api_config({ id: 'all' }).then(res => {
    debugger
    selectList.types=res.print
})
  // console.log('mounted');
});
</script>

<style>
</style>